package com.kkwrite.regimen.provider.service.avtivity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kkwrite.regimen.common.constant.OrderStatusEnum.OrderType;
import com.kkwrite.regimen.common.entity.dto.OutDTO;
import com.kkwrite.regimen.common.entity.dto.activity.ActivityApplyInDTO;
import com.kkwrite.regimen.common.entity.dto.activity.ActivityApplyOutDTO;
import com.kkwrite.regimen.common.entity.dto.activity.ActivityDTO;
import com.kkwrite.regimen.common.entity.dto.order.SubmitOrderInDTO;
import com.kkwrite.regimen.provider.domain.RegActivityApplyDO;
import com.kkwrite.regimen.provider.domain.RegActivityDO;
import com.kkwrite.regimen.provider.domain.RegOrderDO;
import com.kkwrite.regimen.provider.exception.DBNullException;
import com.kkwrite.regimen.provider.repository.RegActivityApplyRepository;
import com.kkwrite.regimen.provider.repository.RegActivityRepository;
import com.kkwrite.regimen.provider.repository.RegOrderRepository;
import com.kkwrite.regimen.provider.service.BaseServiceImpl;
import com.kkwrite.regimen.provider.service.order.OrderService;

/**
 * 活动服务
 *
 * @author jinying
 * 
 */
@Service("activityService")
public class ActivityServiceImpl extends BaseServiceImpl implements
		ActivityService {
	@Resource(name = "regActivityApplyRepository")
	private RegActivityApplyRepository regActivityApplyRepository;

	@Resource(name = "regActivityRepository")
	private RegActivityRepository regActivityRepository;

	@Resource(name = "regOrderRepository")
	private RegOrderRepository regOrderRepository;

	@Resource(name = "orderService")
	private OrderService orderService;

	@Override
	@Transactional(rollbackFor = Exception.class, readOnly = false)
	public ActivityApplyOutDTO insertActivityApply(
			ActivityApplyInDTO activityApplyInDTO, Long userId) {
		RegActivityApplyDO UserIdAndActivityCode = new RegActivityApplyDO();
		UserIdAndActivityCode.setActivityCode(activityApplyInDTO
				.getActivityCode());
		UserIdAndActivityCode.setUserId(userId);
		Optional<RegActivityApplyDO> regActivityApplyReturn = regActivityApplyRepository
				.findOne(Example.of(UserIdAndActivityCode));

		RegActivityApplyDO regActivityApplyDOresult = regActivityApplyReturn.orElseThrow(() -> new RuntimeException());

		if (regActivityApplyDOresult != null) {
			String activityCode = regActivityApplyDOresult.getActivityCode();
			// 根据活动编号查询活动信息
			RegActivityDO regactivityDTO = regActivityRepository
					.findOneByActivityCode(activityCode);

			// 定义返回DTO
			ActivityDTO activityDTO = new ActivityDTO();

			com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(
					regactivityDTO, activityDTO);
			com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(
					regActivityApplyDOresult, activityDTO);

			// 查询订单信息
			RegOrderDO regOrderDO = regOrderRepository
					.findByOrderCode(regActivityApplyDOresult.getOrderCode());
			com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(
					regOrderDO, activityDTO);
			activityDTO.setCounts(regActivityApplyRepository
					.getEffectiveActivityApplyCount(activityCode));
			// 查询有报名信息并且已经支付则报名成功，已经参加此活动
			if (regOrderDO.getPayStatus() == 1) {
				ActivityApplyOutDTO outDto = new ActivityApplyOutDTO("0000",
						"该用户已经参加此活动并支付成功");
				outDto.setActivityDTO(activityDTO);
				return outDto;
			}
			// 查询有报名信息但是未支付成功，已经参加此活动,进行重新支付功能
			if (regOrderDO.getPayStatus() == 0) {
				Map newOrderMap = new HashMap();
				try {
					newOrderMap = orderService
							.continuePay(regActivityApplyDOresult
									.getOrderCode());
				} catch (DBNullException e) {
					e.printStackTrace();
				}
				com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(
						activityApplyInDTO, regActivityApplyDOresult);
				regActivityApplyDOresult.setOrderCode((String) newOrderMap
						.get("orderCode"));
				regActivityApplyRepository
						.saveAndFlush(regActivityApplyDOresult);
				return new ActivityApplyOutDTO("0003", "用户已经报名请继续支付",
						regActivityApplyDOresult.getActivityCode(),
						(String) newOrderMap.get("orderCode"),
						regactivityDTO.getActivityPrice());

			}
		}
		RegActivityApplyDO regActivityApplyDO = new RegActivityApplyDO();
		com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(
				activityApplyInDTO, regActivityApplyDO);
		regActivityApplyDO.setUserId(userId);
		regActivityApplyDO.setDeleted((short) 0);
		RegActivityApplyDO regActivityApplyDOResult = regActivityApplyRepository
				.saveAndFlush(regActivityApplyDO);
		RegActivityDO regActivityDO = regActivityRepository
				.findOneByActivityCode(regActivityApplyDO.getActivityCode());
		// 订单生成入参
		SubmitOrderInDTO submitInDTO = new SubmitOrderInDTO();
		submitInDTO.setItemId(9999);
		submitInDTO.setNum(1);
		submitInDTO.setPhoneNum(activityApplyInDTO.getPhone());
		submitInDTO.setPrice(regActivityDO.getActivityPrice());
		submitInDTO.setShopId(9999);
		submitInDTO.setOrderType(OrderType.ACTIVITY_ORDER_TYPE.getOrderType());
		OutDTO orderOutDto = orderService.save(submitInDTO,
				Integer.valueOf(userId.toString()));
		String orderCode = (String) orderOutDto.getData();
		// 更新报名活动表中订单编号
		regActivityApplyDO.setOrderCode(orderCode);
		regActivityApplyDO.setId(regActivityApplyDOResult.getId());
		regActivityApplyRepository.saveAndFlush(regActivityApplyDO);
		return new ActivityApplyOutDTO("success", "OK", orderCode,
				regActivityDO.getActivityPrice());
	}

	@Override
	public ActivityDTO queryActivity(String activityCode, Long userId) {
		// 根据活动编号查询活动信息
		RegActivityDO regactivityDTO = regActivityRepository
				.findOneByActivityCode(activityCode);
		if (regactivityDTO == null) {
			return new ActivityDTO("0002", "没有此活动编号");
		}
		// 根据活动编号，用户id查询报名信息
		RegActivityApplyDO regActivityApplyDO = regActivityApplyRepository
				.findOneByActivityCodeAndUserId(activityCode, userId);

		// 若没有报名信息，则只返回活动的信息
		if (regActivityApplyDO == null) {
			ActivityDTO activityDTO0001 = new ActivityDTO("0001", "该用户没有参与此活动");
			com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(
					regactivityDTO, activityDTO0001);
			activityDTO0001.setCounts(regActivityApplyRepository
					.getEffectiveActivityApplyCount(activityCode));
			return activityDTO0001;
		}

		// 定义返回DTO
		ActivityDTO activityDTO = new ActivityDTO("success", "OK");

		com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(
				regactivityDTO, activityDTO);
		com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(
				regActivityApplyDO, activityDTO);

		// 查询订单信息
		RegOrderDO regOrderDO = regOrderRepository
				.findByOrderCode(regActivityApplyDO.getOrderCode());
		com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(regOrderDO,
				activityDTO);
		activityDTO.setCounts(regActivityApplyRepository
				.getEffectiveActivityApplyCount(activityCode));
		return activityDTO;
	}
}
